<?php
/**
 * 用户操作类
 * @author zhangyk
 *
 */
class IOSS_User{
	const STATUS_DISABLED = 0;
	const STATUS_ENABLED = 1;
	const BANK_NOT_DELETED = 0;
	private static  $table = 'core_user';
	private static $tabls_bank = 'core_user_bank';
	
	private $user;
	private $bank;
	private $user_updated_cols = array('password'=>false, 'email'=>false, 'qq'=>false, 'weixin'=>false, 'login_time'=>false, 'login_ip'=>false);
	private $bank_cols = array('bank'=>'', 'branch'=>'', 'provice'=>'', 'city'=>'', 'card_no'=>'', 'card_name'=>'');
	
	private function __construct($row){
		$this->user = $row;
		$this->bank = false;
	}
	
	public function __get($key){
		return $this->user[$key];
	}
	
	public function __set($key, $value){
		if(array_key_exists($key, $this->user_updated_cols)){
			$this->user_updated_cols[$key] = true;
			$this->user[$key] = $value;
		}
	}
	
	public function save(){
		$db = IOSS_DB::getInstance();
		$update = array_intersect_key($this->user, array_filter($this->user_updated_cols));
		$update['update_time'] = time();
		if($db->where('id', $this->user['id'])->update(self::$table, $update)){
			$this->user['update_time'] = $update['update_time'];
			array_walk($this->user_updated_cols, function (&$v){ $v = false;});
		}
	}
	
	/**
	 * 获取用户银行卡信息， 没有可用信息返回null
	 * @return stdClass
	 */
	public function getBank(){
		if($this->bank === false){
			$db = IOSS_DB::getInstance();
			$db->where('user_id', $this->user['id']);
			$db->where('deleted', self::BANK_NOT_DELETED);
			$db->order_by('id', 'DESC');
			$db->limit(1);
			$this->bank = $db->get(self::$tabls_bank)->row();
		}
		return $this->bank;
	}

	/**
	 * 获取用户关联的平台自有银行卡信息
	 * @return stdClass
	 */
	public function getSelfBank(){
		$db = IOSS_DB::getInstance();
		if($this->user['set_bank_code']){	//该用户已经被指定了平台的银行卡,则用指定的code的平台自有银行卡信息
			$db->where('code', $this->user['set_bank_code']);
		}else{	//没有指定平台银行卡，使用平台默认的银行卡信息
			$db->where('is_default', 1);
		}
		$db->where('status', 1);
		$plat_bank = $db->get('core_bank_info')->row();
		return $plat_bank;
	}
	
	public function addBank($info){
		$vo = new stdClass();
		foreach ($this->bank_cols as $k=>$v){
			$vo->{$k} = isset($info[$k]) ? $info[$k] : $v;
		}
		$vo->user_id = $this->user['id'];
		$vo->deleted = self::BANK_NOT_DELETED;
		$vo->update_time = time();
		$vo->create_time = time();
		$db = IOSS_DB::getInstance();
		if($db->insert(self::$tabls_bank, $vo)){
			$this->bank = false;
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 通过id获取用户信息
	 * @param int $id
	 * @return IOSS_User
	 */
	public static  function getById($id){
		$db = IOSS_DB::getInstance();
		$row = $db->where('id', $id)->get(self::$table)->row_array();
		if($row){
			return  new self($row);
		}else{
			return null;
		}
	}

	/**
	 * 通过account获取用户信息
	 * @param int $id
	 * @return IOSS_User
	 */
	public static  function getByAccount($account){
		$db = IOSS_DB::getInstance();
		$row = $db->where('account', $account)->get(self::$table)->row_array();
		if($row){
			return  new self($row);
		}else{
			return null;
		}
	}

	/**
	* 获取$user_id的所有直接好友数量
	*/
	public static function getFriendNum($user_id){
		$db = IOSS_DB::getInstance();
		$db->select('count(*) num');
		$db->from(self::$table);
		$db->where('p_id',$user_id);
		$result = $db->get()->result();
		return $result[0]->num;
	}
	
	/**
	 * 通过account获取用户user,p1_user_id,p2_user_id
	 * @param string $account
	 */
	public static function getUserIdsByAccount($account){
	    $db = IOSS_DB::getInstance();
	    $db->select('user.id as user_id,user.p_id as p1_user_id,user2.p_id as p2_user_id');
	    $db->from('user');
	    $db->join('user as user2','user.p_id=user2.id','LEFT');
	    $db->where('user.account',$account);
	    return $db->get()->result();
	}
	
	/**
	 * 更新用户提成余额
	 * @param int $id
	 * @param decimal $addMoney
	 */
	public static function updateCommissions($id,$addMoney){
	    $db = IOSS_DB::getInstance();
	    $db->where('id',$id);
	    $db->set('commissions',"commissions+$addMoney",FALSE);
	    $db->set('commissions_total',"commissions_total+$addMoney",FALSE);
	    return $db->update(self::$table);
	}
	
	/**
	 * 用户登录: 
	 * 成功返回用户信息，失败返回false
	 * @param string $account
	 * @param string $password
	 * @param string $ip
	 * @return IOSS_User
	 */
	public static function login($account, $password, $ip = ''){
		$db = IOSS_DB::getInstance();
		$row = $db->where('account', $account)->where('status', self::STATUS_ENABLED)->get(self::$table)->row_array();
		if($row && self::verifyPassword($password, $row['password'])){
			$user = new self($row);
			//记录登录IP和时间
			$user->login_time = time();
			$user->login_ip = $ip;
			$user->save();

			return $user;
		}
		return false;
	}
	
	/**
	 * 用户注册：
	 * 成功返回用户id，失败时返回false
	 * @param string $account 账号
	 * @param string $password  密码
	 * @param string $p_id  上级id
	 * @param string $ip IP地址
	 * @return int
	 */
	public static function register($account, $password, $p_id, $ip = ''){
		//if(!self::isLegalAccount($account) || !self::isLegalPassword($password)){
		//	return false;
		//}
		$db = IOSS_DB::getInstance();
		$time = time();
		$vo = new stdClass();
		$vo->account = $account;
		$vo->password = self::hashPassword($password);
		$vo->game_key = md5(rand()); //游戏平台使用的密码
		$vo->status = self::STATUS_ENABLED;
		$vo->p_id = $p_id;
		$vo->reg_ip = $ip;
		$vo->login_ip = $ip;
		$vo->login_time = $time;
		$vo->create_time = $time;
		$vo->update_time = $time;

		if($db->insert(self::$table, $vo)){
			return $db->insert_id();
		}else{
			return false;
		}
	}
	
	/**
	 * 修改密码
	 * @param id int 用户id
	 * @param password 用户输入的新密码
	 * @return boolean
	 */
	public static function modifyPassword($id,$password){
		$db = IOSS_DB::getInstance();
		$db->where('id',$id);
		$db->set(array(
			'password'=>self::hashPassword($password),
			'update_time'=>time()
		));
		$db->update(self::$table);
		if($db->affected_rows()>0){
			return true;
		}else{
			return false;
		}
	}
	

	/**
	 * 生成hash后的密码
	 * @param string $pass 用户输入的原始密码
	 * @return string
	 */
	public static function hashPassword($password){
		return password_hash($password, PASSWORD_BCRYPT);  // 注意： password_hash() 函数使用PASSWORD_BCRYPT模式时，支持密码最大长度是72，超过会被截断
	}

	/**
	 * 验证用户密码
	 * @param string $pass 用户输入的原始密码
	 * @param string $hash_pass  hash后的密码
	 * @return boolean
	 */
	public static function verifyPassword($password, $hash){
		return password_verify($password, $hash);
	}
		
	static function isLegalAccount($account){
		return strlen($account) > 4 && strlen($account) < 32;
	}
	
	static function isLegalEmail($email){
		return strlen($email) > 4 && strlen($email) < 255 &&  preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
	}
	
	static function isLegalPassword($password){
		return strlen($password) > 6 && strlen($password) < 72;
	}
	
	static function isExistAccount($account){
		$db = IOSS_DB::getInstance();
		return $db->get_where(self::$table, array('account' => $account))->num_rows() !== 0;
	}

}
